//
// Created by 86135 on 2025-06-06.
//

#include "parser.h"
#include <stdbool.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

// 当前 token
Token currentToken;

// 定义错误类型
typedef enum {
    ERROR_MISSING_LEFT_PAREN,
    ERROR_MISSING_RIGHT_PAREN,
    ERROR_MISSING_SEMICOLON,
    ERROR_UNKNOWN_EXPR,
    ERROR_MISSING_RIGHT_BRACE,
    ERROR_UNKNOWN_STATEMENT,

    //v4
    ERROR_MISSING_IDENTIFIER,
    ERROR_MISSING_OPERATOR,
    ERROR_MISSING_OPERAND,
    ERROR_INVALID_ASSIGNMENT,
    ERROR_MISSING_CONDITION,
    ERROR_MISSING_RIGHT_BRACKET,

    //v5
    ERROR_MISSING_WHILE_CONDITION,
    ERROR_MISSING_FOR_PARTS,
    ERROR_MISSING_BREAK_SEMICOLON,
    ERROR_MISSING_CONTINUE_SEMICOLON,

    //v6
    ERROR_MISSING_RETURN_SEMICOLON,
    ERROR_MISSING_FUNCTION_NAME,
    ERROR_MISSING_LEFT_PAREN_AFTER_NAME,
    ERROR_MISSING_RIGHT_PAREN_AFTER_ARGS,
    ERROR_EXPECTED_TYPE_SPECIFIER,
    ERROR_EXPECTED_IDENTIFIER,
    ERROR_MISSING_SEMICOLON_AFTER_DECL,
    ERROR_INVALID_RETURN,
    ERROR_MISSING_TYPE_SPECIFIER,          // 新增
    ERROR_MISSING_PARAMETER_NAME,          // 新增
    ERROR_MISSING_RETURN_TYPE,             // 新增
    ERROR_MISSING_RIGHT_PAREN_AFTER_PARAMS,// 新增
    ERROR_MISSING_LEFT_BRACE,              // 新增
    ERROR_EMPTY_FUNCTION_BODY,             // 新增

    // todo..
} ParserErrorType;

ASTNode* parse_factor();
ASTNode* parse_term();
ASTNode* parse_expr();
ASTNode* parse_statement();
ASTNode* parse_program();
ASTNode* parse_block();

ASTNode* parse_assignment();
ASTNode* parse_logical_or();
ASTNode* parse_logical_and();
ASTNode* parse_equality();
ASTNode* parse_relational();
ASTNode* parse_additive();

ASTNode* parse_type_specifier();
ASTNode* parse_parameter_list();
ASTNode* parse_argument_list();
ASTNode* parse_function_def();
ASTNode* parse_declaration();
ASTNode* parse_function_call();

/********************************************************************************************
 *                                         辅助方法										    *
 ********************************************************************************************/
// 获取下一个 token
static void advance() {
    currentToken = lexerIdentifier();
}
// 查看当前 token 的类型
static TokenType peek() {
    return currentToken.type;
}
// 匹配指定类型的 token
static bool match(TokenType type) {
    if (currentToken.type == type) {
        advance();
        return true;
    }
    return false;
}
/********************************************************************************************
 *                                         错误处理										    *
 ********************************************************************************************/
// 处理解析错误
void handleParserError(ParserErrorType errorType) {
    switch (errorType) {
        case ERROR_MISSING_LEFT_PAREN:
            printf("Error: Expected '(' after 'if' at line %d\n", currentToken.line);
            break;
        case ERROR_MISSING_RIGHT_PAREN:
            printf("Error: Expected ')' after condition at line %d\n", currentToken.line);
            break;
        case ERROR_MISSING_SEMICOLON:
            printf("Error: Expected ';' after expression at line %d\n", currentToken.line);
            break;
        case ERROR_UNKNOWN_EXPR:
            printf("Error: Unknown expression at line %d\n", currentToken.line);
            break;
        case ERROR_MISSING_RIGHT_BRACE:
            printf("Error: Expected '}' at line %d\n", currentToken.line);
            break;
        case ERROR_UNKNOWN_STATEMENT:
            printf("Error: Unknown statement at line %d\n", currentToken.line);
            break;

        //v4
        case ERROR_MISSING_IDENTIFIER:
            printf("Error: Expected identifier at line %d\n", currentToken.line);
            break;
        case ERROR_MISSING_OPERATOR:
            printf("Error: Expected operator at line %d\n", currentToken.line);
            break;
        case ERROR_MISSING_OPERAND:
            printf("Error: Expected operand at line %d\n", currentToken.line);
            break;
        case ERROR_INVALID_ASSIGNMENT:
            printf("Error: Invalid assignment target at line %d\n", currentToken.line);
            break;
        case ERROR_MISSING_CONDITION:
            printf("Error: Missing condition for 'if' statement at line %d\n", currentToken.line);
            break;
        case ERROR_MISSING_RIGHT_BRACKET:
            printf("Error: Expected ']' at line %d\n", currentToken.line);
            break;

        //v5
        case ERROR_MISSING_WHILE_CONDITION:
            printf("Error: Missing condition for 'while' at line %d\n", currentToken.line);
            break;
        case ERROR_MISSING_FOR_PARTS:
            printf("Error: Missing parts in 'for' statement at line %d\n", currentToken.line);
            break;
        case ERROR_MISSING_BREAK_SEMICOLON:
            printf("Error: Missing ';' after 'break' at line %d\n", currentToken.line);
            break;
        case ERROR_MISSING_CONTINUE_SEMICOLON:
            printf("Error: Missing ';' after 'continue' at line %d\n", currentToken.line);
            break;

        //v6
        case ERROR_MISSING_RETURN_SEMICOLON:
            printf("Error: Missing ';' after return at line %d\n", currentToken.line);
            break;
        case ERROR_MISSING_FUNCTION_NAME:
            printf("Error: Missing function name at line %d\n", currentToken.line);
            break;
        case ERROR_MISSING_LEFT_PAREN_AFTER_NAME:
            printf("Error: Missing '(' after function name at line %d\n", currentToken.line);
            break;
        case ERROR_MISSING_RIGHT_PAREN_AFTER_ARGS:
            printf("Error: Missing ')' after arguments at line %d\n", currentToken.line);
            break;
        case ERROR_EXPECTED_TYPE_SPECIFIER:
            printf("Error: Expected type specifier at line %d\n", currentToken.line);
            break;
        case ERROR_EXPECTED_IDENTIFIER:
            printf("Error: Expected identifier at line %d\n", currentToken.line);
            break;
        case ERROR_MISSING_SEMICOLON_AFTER_DECL:
            printf("Error: Missing ';' after declaration at line %d\n", currentToken.line);
            break;
        case ERROR_INVALID_RETURN:
            printf("Error: Invalid return statement at line %d\n", currentToken.line);
            break;
        case ERROR_MISSING_TYPE_SPECIFIER:
            printf("Error: Missing type specifier at line %d\n", currentToken.line);
            break;
        case ERROR_MISSING_PARAMETER_NAME:
            printf("Error: Missing parameter name at line %d\n", currentToken.line);
            break;
        case ERROR_MISSING_RETURN_TYPE:
            printf("Error: Missing return type at line %d\n", currentToken.line);
            break;
        case ERROR_MISSING_RIGHT_PAREN_AFTER_PARAMS:
            printf("Error: Missing ')' after parameters at line %d\n", currentToken.line);
            break;
        case ERROR_MISSING_LEFT_BRACE:
            printf("Error: Missing '{' after function header at line %d\n", currentToken.line);
            break;
        case ERROR_EMPTY_FUNCTION_BODY:
            printf("Error: Empty function body at line %d\n", currentToken.line);
            break;
            // todo..
        default:
            printf("Unknown parser error at line %d\n", currentToken.line);
    }
}
/********************************************************************************************
 *                                         增删结点										    *
 ********************************************************************************************/
// 释放 AST 节点及其子节点的内存
void freeASTNode(ASTNode* node) {
    if (node == NULL) return;

    // 释放节点特定资源
    switch (node->type) {
        case AST_IDENTIFIER:
            free(node->data.identifier.name);
            break;
            // ... 其他类型处理
    }

    // 释放子节点
    for (int i = 0; i < node->childCount; i++) {
        freeASTNode(node->children[i]);
    }

    if (node->children) {
        free(node->children);
    }

    free(node);
}

// 创建新的AST节点
ASTNode* createASTNode(ASTNodeType type, int childCount, int line) {
    ASTNode* node = (ASTNode*)malloc(sizeof(ASTNode));
    if (!node) {
        fprintf(stderr, "Memory allocation failed\n");
        exit(EXIT_FAILURE);
    }
    node->type = type;
    node->line = line;
    node->childCount = childCount;

    if (childCount > 0) {
        node->children = (ASTNode**)malloc(childCount * sizeof(ASTNode*));
        if (!node->children) {
            fprintf(stderr, "Memory allocation failed\n");
            exit(EXIT_FAILURE);
        }
    } else {
        node->children = NULL;
    }

    return node;
}

// 创建 IF 语句节点
ASTNode* createIfNode(ASTNode* condition, ASTNode* ifBody, ASTNode* elseBody, int line) {
    ASTNode* node = createASTNode(AST_IF, 3, line);
    node->data.ifStmt.condition = condition;
    node->data.ifStmt.ifBody = ifBody;
    node->data.ifStmt.elseBody = elseBody;
    node->children[0] = condition;
    node->children[1] = ifBody;
    node->children[2] = elseBody;
    return node;
}

// 创建二元表达式节点
ASTNode* createBinaryExprNode(ASTNode* left, ASTNode* right, TokenType operator, int line) {
    ASTNode* node = createASTNode(AST_BINARY_EXPR, 2, line);
    node->data.binaryExpr.left = left;
    node->data.binaryExpr.right = right;
    node->data.binaryExpr.operator = operator;
    node->children[0] = left;
    node->children[1] = right;
    return node;
}

// 创建字面量节点
ASTNode* createLiteralNode(double value, int line) {
    ASTNode* node = createASTNode(AST_LITERAL, 0, line);
    node->data.literal.value = value;
    return node;
}

// 创建表达式语句节点
ASTNode* createExprStmtNode(ASTNode* expr, int line) {
    ASTNode* node = createASTNode(AST_EXPR_STMT, 1, line);
    node->data.exprStmt.expr = expr;
    node->children[0] = expr;
    return node;
}

// 创建块语句节点
ASTNode* createBlockNode(int stmtCount, int line) {
    ASTNode* node = createASTNode(AST_BLOCK, stmtCount, line);
    node->data.block.stmtCount = stmtCount;
    node->data.block.statements = node->children;
    return node;
}

// 创建空语句节点
ASTNode* createEmptyStmtNode(int line) {
    ASTNode* node = createASTNode(AST_EMPTY_STMT, 0, line);
    return node;
}

// 创建标识符节点
ASTNode* createIdentifierNode(const char* name, int length, int line) {
    ASTNode* node = createASTNode(AST_IDENTIFIER, 0, line);

    // 分配内存并复制字符串
    node->data.identifier.name = (char*)malloc(length + 1);
    if (!node->data.identifier.name) {
        fprintf(stderr, "Memory allocation failed\n");
        exit(EXIT_FAILURE);
    }

    strncpy(node->data.identifier.name, name, length);
    node->data.identifier.name[length] = '\0';
    return node;
}

// 创建赋值节点
ASTNode* createAssignmentNode(ASTNode* left, ASTNode* right, int line) {
    ASTNode* node = createASTNode(AST_ASSIGNMENT, 2, line);
    node->data.assignment.left = left;
    node->data.assignment.right = right;
    node->data.assignment.operator = TOKEN_EQUAL;
    node->children[0] = left;
    node->children[1] = right;
    return node;
}

// 创建逻辑或节点
ASTNode* createLogicalOrNode(ASTNode* left, ASTNode* right, int line) {
    ASTNode* node = createASTNode(AST_LOGICAL_OR, 2, line);
    node->data.logicalOr.left = left;
    node->data.logicalOr.right = right;
    node->data.logicalOr.operator = TOKEN_PIPE_PIPE;
    node->children[0] = left;
    node->children[1] = right;
    return node;
}

// 创建逻辑与节点
ASTNode* createLogicalAndNode(ASTNode* left, ASTNode* right, int line) {
    ASTNode* node = createASTNode(AST_LOGICAL_AND, 2, line);
    node->data.logicalOr.left = left;
    node->data.logicalOr.right = right;
    node->data.logicalOr.operator = TOKEN_AMPER_AMPER;
    node->children[0] = left;
    node->children[1] = right;
    return node;
}

// 创建相等比较节点
ASTNode* createEqualityNode(ASTNode* left, ASTNode* right, TokenType operator, int line){
    ASTNode* node = createASTNode(AST_EQUALITY, 2, line);
    node->data.logicalOr.left = left;
    node->data.logicalOr.right = right;
    node->data.logicalOr.operator = operator;
    node->children[0] = left;
    node->children[1] = right;
    return node;
}

// 创建关系比较节点
ASTNode* createRelationalNode(ASTNode* left, ASTNode* right, TokenType operator, int line) {
    ASTNode* node = createASTNode(AST_RELATIONAL, 2, line);
    node->data.relational.left = left;
    node->data.relational.right = right;
    node->data.relational.operator = operator;
    node->children[0] = left;
    node->children[1] = right;
    return node;
}

// 创建while节点
ASTNode* createWhileNode(ASTNode* condition, ASTNode* body, int line) {
    ASTNode* node = createASTNode(AST_WHILE, 2, line);
    node->data.whileStmt.condition = condition;
    node->data.whileStmt.body = body;
    node->children[0] = condition;
    node->children[1] = body;
    return node;
}

// 创建for节点
ASTNode* createForNode(ASTNode* init, ASTNode* condition, ASTNode* update, ASTNode* body, int line) {
    ASTNode* node = createASTNode(AST_FOR, 4, line);
    node->data.forStmt.init = init;
    node->data.forStmt.condition = condition;
    node->data.forStmt.update = update;
    node->data.forStmt.body = body;
    node->children[0] = init;
    node->children[1] = condition;
    node->children[2] = update;
    node->children[3] = body;
    return node;
}
// 创建 break 节点
ASTNode* createBreakNode(int line) {
    return createASTNode(AST_BREAK, 0, line);
}

// 创建 continue 节点
ASTNode* createContinueNode(int line) {
    return createASTNode(AST_CONTINUE, 0, line);
}

//v6
ASTNode* createFunctionDefNode(ASTNode* returnType, ASTNode* name, ASTNode* params, ASTNode* body, int line) {
    ASTNode* node = createASTNode(AST_FUNCTION_DEF, 4, line);
    node->data.functionDef.returnType = returnType;
    node->data.functionDef.functionName = name;
    node->data.functionDef.params = params;
    node->data.functionDef.body = body;
    node->children[0] = returnType;
    node->children[1] = name;
    node->children[2] = params;
    node->children[3] = body;
    return node;
}

ASTNode* createFunctionCallNode(ASTNode* name, ASTNode* args, int line) {
    ASTNode* node = createASTNode(AST_FUNCTION_CALL, 2, line);
    node->data.functionCall.functionName = name;
    node->data.functionCall.arguments = args;
    node->children[0] = name;
    node->children[1] = args;
    return node;
}

ASTNode* createReturnNode(ASTNode* expr, int line) {
    ASTNode* node = createASTNode(AST_RETURN, (expr ? 1 : 0), line);
    node->data.returnStmt.expr = expr;
    if (expr) node->children[0] = expr;
    return node;
}

ASTNode* createDeclarationNode(ASTNode* type, ASTNode* id, ASTNode* init, int line) {
    ASTNode* node = createASTNode(AST_DECLARATION, (init ? 3 : 2), line);
    node->data.declaration.typeSpec = type;
    node->data.declaration.identifier = id;
    node->data.declaration.initExpr = init;
    node->children[0] = type;
    node->children[1] = id;
    if (init) node->children[2] = init;
    return node;
}

ASTNode* createParameterNode(ASTNode* type, ASTNode* id, int line) {
    ASTNode* node = createASTNode(AST_PARAMETER, 2, line);
    node->data.parameter.typeSpec = type;
    node->data.parameter.identifier = id;
    node->children[0] = type;
    node->children[1] = id;
    return node;
}

ASTNode* createTypeSpecifierNode(TokenType type, int line) {
    ASTNode* node = createASTNode(AST_TYPE_SPECIFIER, 0, line);
    node->data.typeSpecifier.type = type;
    return node;
}

ASTNode* createArgumentListNode(int count, int line) {
    ASTNode* node = createASTNode(AST_ARGUMENT_LIST, count, line);
    node->data.argumentList.count = count;
    node->data.argumentList.items = node->children;
    return node;
}
/********************************************************************************************
*                                         解析非终结符									    *
********************************************************************************************/
//-------------------------------------->解析函数<-------------------------------------------*/
// 解析类型说明符
ASTNode* parse_type_specifier() {
    switch (peek()) {
        case TOKEN_INT:
        case TOKEN_CHAR:
        case TOKEN_FLOAT:
        case TOKEN_DOUBLE:
        case TOKEN_VOID: {
            ASTNode* node = createTypeSpecifierNode(peek(), currentToken.line);
            advance();
            return node;
        }
        default:
            handleParserError(ERROR_EXPECTED_TYPE_SPECIFIER);
            return NULL;
    }
}

// 重构参数列表解析
ASTNode* parse_parameter_list() {
    int line = currentToken.line;
    ASTNode** params = NULL;
    int paramCount = 0;

    // 在函数开头添加空列表检查
    if (peek() == TOKEN_RIGHT_PAREN) {
        return createASTNode(AST_PARAMETER_LIST, 0, line);
    }

    while (peek() != TOKEN_RIGHT_PAREN && peek() != TOKEN_EOF) {
        // 解析类型说明符
        ASTNode* typeSpec = parse_type_specifier();
        if (!typeSpec) {
            handleParserError(ERROR_MISSING_TYPE_SPECIFIER);
            break;
        }

        // 解析标识符
        if (peek() != TOKEN_IDENTIFIER) {
            handleParserError(ERROR_MISSING_PARAMETER_NAME);
            break;
        }

        ASTNode* id = createIdentifierNode(currentToken.start, currentToken.length, currentToken.line);
        advance(); // 消耗标识符

        // 创建参数节点
        ASTNode* param = createParameterNode(typeSpec, id, line);

        // 添加到参数列表
        params = realloc(params, (paramCount + 1) * sizeof(ASTNode*));
        params[paramCount++] = param;

        // 如果是逗号，继续；否则结束
        if (peek() != TOKEN_COMMA) break;
        advance(); // 消耗逗号
    }

    // 创建参数列表容器节点
    ASTNode* paramList = createASTNode(AST_PARAMETER_LIST, paramCount, line);
    for (int i = 0; i < paramCount; i++) {
        paramList->children[i] = params[i];
    }
    free(params);

    return paramList;
}

// 解析参数列表（函数调用）
ASTNode* parse_argument_list() {
    int line = currentToken.line;
    int argCount = 0;
    ASTNode** args = NULL;

    // 处理空参数列表的情况
    if (peek() == TOKEN_RIGHT_PAREN) {
        return createASTNode(AST_ARGUMENT_LIST, 0, line);
    }

    while (1) {
        ASTNode* expr = parse_expr();
        if (!expr) return NULL;

        // 添加参数到列表
        args = realloc(args, (argCount + 1) * sizeof(ASTNode*));
        args[argCount++] = expr;

        // 检查是否还有更多参数
        switch (peek()) {
            case TOKEN_COMMA:
                advance(); // 消耗逗号
                continue;
            case TOKEN_RIGHT_PAREN:
                break;
            default:
                handleParserError(ERROR_UNKNOWN_EXPR);
                return NULL;
        }
        break;
    }

    // 创建参数列表节点
    ASTNode* argList = createArgumentListNode(argCount, line);
    if (argCount > 0) {
        memcpy(argList->children, args, argCount * sizeof(ASTNode*));
    }
    free(args);
    return argList;
}

// 重构函数定义解析
ASTNode* parse_function_def() {
    int line = currentToken.line;

    // 解析返回类型
    ASTNode* returnType = parse_type_specifier();
    if (!returnType) {
        handleParserError(ERROR_MISSING_RETURN_TYPE);
        return NULL;
    }

    // 解析函数名
    if (peek() != TOKEN_IDENTIFIER) {
        handleParserError(ERROR_MISSING_FUNCTION_NAME);
        return NULL;
    }
    ASTNode* funcName = createIdentifierNode(currentToken.start, currentToken.length, line);
    advance();

    // 检查左括号
    if (!match(TOKEN_LEFT_PAREN)) {
        handleParserError(ERROR_MISSING_LEFT_PAREN_AFTER_NAME);
        return NULL;
    }

    // 解析参数列表
    ASTNode* paramList = parse_parameter_list();

    // 检查右括号
    if (!match(TOKEN_RIGHT_PAREN)) {
        handleParserError(ERROR_MISSING_RIGHT_PAREN_AFTER_PARAMS);
        return NULL;
    }

    // 解析函数体
    if (!match(TOKEN_LEFT_BRACE)) {
        handleParserError(ERROR_MISSING_LEFT_BRACE);
        return NULL;
    }

    ASTNode* body = parse_block();
    if (!body) {
        handleParserError(ERROR_EMPTY_FUNCTION_BODY);
        return NULL;
    }

    return createFunctionDefNode(returnType, funcName, paramList, body, line);
}

// 解析函数调用
ASTNode* parse_function_call(ASTNode* identifier) {
    int line = currentToken.line;
    advance(); // 消耗 '('

    ASTNode* args = parse_argument_list();
    if (!args) return NULL;

    switch (peek()) {
        case TOKEN_RIGHT_PAREN:
            advance();
            break;
        default:
            handleParserError(ERROR_MISSING_RIGHT_PAREN_AFTER_ARGS);
            return NULL;
    }

    return createFunctionCallNode(identifier, args, line);
}
// 解析变量声明
ASTNode* parse_declaration() {
    int line = currentToken.line;

    // 解析类型说明符
    ASTNode* type = parse_type_specifier();
    if (!type) return NULL;

    // 解析标识符
    ASTNode* id = NULL;
    switch (peek()) {
        case TOKEN_IDENTIFIER:
            id = createIdentifierNode(
                    currentToken.start,
                    currentToken.length,
                    currentToken.line
            );
            advance();
            break;
        default:
            handleParserError(ERROR_EXPECTED_IDENTIFIER);
            return NULL;
    }

    // 检查是否有初始化表达式
    ASTNode* init = NULL;
    switch (peek()) {
        case TOKEN_EQUAL:
            advance(); // 消耗 '='
            init = parse_expr();
            if (!init) return NULL;
            break;
        default:
            // 没有初始化表达式
            break;
    }

    // 解析结束分号
    switch (peek()) {
        case TOKEN_SEMICOLON:
            advance();
            break;
        default:
            handleParserError(ERROR_MISSING_SEMICOLON_AFTER_DECL);
            return NULL;
    }

    return createDeclarationNode(type, id, init, line);
}

//-------------------------------------->解析表达式<-----------------------------------------*/
// 解析 factor
ASTNode* parse_factor() {
    int line = currentToken.line;  // 在消耗token前记录行号

    switch (peek()) {
        case TOKEN_NUMBER: {
            char buffer[100];
            strncpy(buffer, currentToken.start, currentToken.length);
            buffer[currentToken.length] = '\0';
            double value = strtod(buffer, NULL);
            advance();
            return createLiteralNode(value, line);
        }

        case TOKEN_IDENTIFIER: {
            ASTNode* id = createIdentifierNode(currentToken.start, currentToken.length, line);
            advance();

            // 检查是否是函数调用
            if (match(TOKEN_LEFT_PAREN)) {
                ASTNode* args = parse_argument_list();
                if (!match(TOKEN_RIGHT_PAREN)) {
                    handleParserError(ERROR_MISSING_RIGHT_PAREN_AFTER_ARGS);
                    return NULL;
                }
                return createFunctionCallNode(id, args, currentToken.line);
            }
            return id;
        }

        case TOKEN_LEFT_PAREN:{
            line = currentToken.line;  // 记录左括号的行号
            advance(); // 消耗 '('
            ASTNode* expr = parse_expr();
            if (!match(TOKEN_RIGHT_PAREN)) {
                handleParserError(ERROR_MISSING_RIGHT_PAREN);
                return NULL;
            }
            return expr;
        }

        case TOKEN_CHARACTER: {
            // 处理字符字面量
            const char* content = currentToken.start + 1; // 跳过开头的单引号
            int length = currentToken.length - 2; // 去掉两边的单引号

            // 简化处理：取第一个字符（实际应该处理转义字符）
            char charValue = (length > 0) ? *content : '\0';

            double value = (double)charValue;
            advance(); // 消耗token
            return createLiteralNode(value, line);
        }


        default:
            handleParserError(ERROR_UNKNOWN_EXPR);
            return NULL;
    }
}

// 解析 term
ASTNode* parse_term() {
    ASTNode* left = parse_factor();

    while (true) {
        int line = currentToken.line;
        switch (peek()) {
            case TOKEN_STAR:
            case TOKEN_SLASH:
            case TOKEN_PERCENT: {
                // 直接使用 TokenType 作为运算符
                TokenType operator = peek();
                advance();
                ASTNode* right = parse_factor();
                left = createBinaryExprNode(left, right, operator, line);
                break;
            }
            default:
                return left;
        }
    }
}

// 解析表达式
ASTNode* parse_expr() {
    return parse_assignment();
}

// 解析赋值表达式
ASTNode* parse_assignment() {
    ASTNode* left = parse_logical_or();
    int line = currentToken.line;

    if (match(TOKEN_EQUAL)) {
        ASTNode* right = parse_assignment(); // 右递归处理连续赋值
        return createAssignmentNode(left, right, line);
    }

    return left;
}

// 解析逻辑或
ASTNode* parse_logical_or() {
    ASTNode* left = parse_logical_and();

    while (true) {
        int line = currentToken.line;
        if (match(TOKEN_PIPE_PIPE)) {
            ASTNode* right = parse_logical_and();
            left = createLogicalOrNode(left, right, line);
        } else {
            return left;
        }
    }
}

// 解析逻辑与
ASTNode* parse_logical_and() {
    ASTNode* left = parse_equality();

    while (true) {
        int line = currentToken.line;
        if (match(TOKEN_AMPER_AMPER)) {
            ASTNode* right = parse_equality();
            left = createLogicalAndNode(left, right, line);
        } else {
            return left;
        }
    }
}

// 解析相等比较
ASTNode* parse_equality() {
    ASTNode* left = parse_relational();

    while (true) {
        int line = currentToken.line;
        switch (peek()) {
            case TOKEN_EQUAL_EQUAL:
            case TOKEN_BANG_EQUAL: {
                TokenType operator = peek();
                advance();
                ASTNode* right = parse_relational();
                left = createEqualityNode(left, right, operator, line);
                break;
            }
            default:
                return left;
        }
    }
}

// 解析关系比较
ASTNode* parse_relational() {
    ASTNode* left = parse_additive();

    while (true) {
        int line = currentToken.line;
        switch (peek()) {
            case TOKEN_LESS:
            case TOKEN_LESS_EQUAL:
            case TOKEN_GREATER:
            case TOKEN_GREATER_EQUAL: {
                TokenType operator = peek();
                advance();
                ASTNode* right = parse_additive();
                left = createRelationalNode(left, right, operator, line);
                break;
            }
            default:
                return left;
        }
    }
}

// 解析加减
ASTNode* parse_additive() {
    ASTNode* left = parse_term();

    while (true) {
        int line = currentToken.line;
        switch (peek()) {
            case TOKEN_PLUS:
            case TOKEN_MINUS: {
                // 直接使用 TokenType 作为运算符
                TokenType operator = peek();
                advance();
                ASTNode* right = parse_term();
                left = createBinaryExprNode(left, right, operator, line);
                break;
            }
            default:
                return left;
        }
    }
}
/*-------------------------------------->解析语句<-----------------------------------------*/
// 解析语句
ASTNode* parse_statement() {
    int line = currentToken.line;  // 记录语句起始行号
    switch (peek()) {
        case TOKEN_IF: {
            line = currentToken.line;  // 记录if关键字的行号
            advance(); // 消耗 'if'

            if (!match(TOKEN_LEFT_PAREN)) {
                handleParserError(ERROR_MISSING_LEFT_PAREN);
                return NULL;
            }

            ASTNode* condition = parse_expr();
            if (!condition) {
                // 表达式解析失败，尝试恢复
                while (peek() != TOKEN_RIGHT_PAREN && peek() != TOKEN_EOF) {
                    advance();
                }
                if (peek() == TOKEN_RIGHT_PAREN) advance();
            }

            if (!match(TOKEN_RIGHT_PAREN)) {
                handleParserError(ERROR_MISSING_RIGHT_PAREN);
                return NULL;
            }

            ASTNode* ifBody = parse_statement();

            ASTNode* elseBody = NULL;
            if (match(TOKEN_ELSE)) {
                elseBody = parse_statement();
            }

            return createIfNode(condition, ifBody, elseBody, line);
        }

        //v5
        case TOKEN_WHILE: {
            line = currentToken.line;
            advance(); // 消耗 'while'

            if (!match(TOKEN_LEFT_PAREN)) {
                handleParserError(ERROR_MISSING_LEFT_PAREN);
                return NULL;
            }

            ASTNode* condition = parse_expr();
            if (!condition) {
                // 错误恢复
                while (peek() != TOKEN_RIGHT_PAREN && peek() != TOKEN_EOF) advance();
                if (peek() == TOKEN_RIGHT_PAREN) advance();
            }

            if (!match(TOKEN_RIGHT_PAREN)) {
                handleParserError(ERROR_MISSING_RIGHT_PAREN);
                return NULL;
            }

            ASTNode* body = parse_statement();
            return createWhileNode(condition, body, line);
        }

        case TOKEN_FOR: {
            line = currentToken.line;
            advance(); // 消耗 'for'

            if (!match(TOKEN_LEFT_PAREN)) {
                handleParserError(ERROR_MISSING_LEFT_PAREN);
                return NULL;
            }

            // 初始化表达式 (可选)
            ASTNode* init = NULL;
            if (peek() != TOKEN_SEMICOLON) {
                init = parse_expr();
            }
            if (!match(TOKEN_SEMICOLON)) {
                handleParserError(ERROR_MISSING_SEMICOLON);
                return NULL;
            }

            // 条件表达式 (可选)
            ASTNode* condition = NULL;
            if (peek() != TOKEN_SEMICOLON) {
                condition = parse_expr();
            }
            if (!match(TOKEN_SEMICOLON)) {
                handleParserError(ERROR_MISSING_SEMICOLON);
                return NULL;
            }

            // 更新表达式 (可选)
            ASTNode* update = NULL;
            if (peek() != TOKEN_RIGHT_PAREN) {
                update = parse_expr();
            }
            if (!match(TOKEN_RIGHT_PAREN)) {
                handleParserError(ERROR_MISSING_RIGHT_PAREN);
                return NULL;
            }

            ASTNode* body = parse_statement();
            return createForNode(init, condition, update, body, line);
        }

        case TOKEN_BREAK: {
            line = currentToken.line;
            advance(); // 消耗 'break'
            if (!match(TOKEN_SEMICOLON)) {
                handleParserError(ERROR_MISSING_SEMICOLON);
                return NULL;
            }
            return createBreakNode(line);
        }

        case TOKEN_CONTINUE: {
            line = currentToken.line;
            advance(); // 消耗 'continue'
            if (!match(TOKEN_SEMICOLON)) {
                handleParserError(ERROR_MISSING_SEMICOLON);
                return NULL;
            }
            return createContinueNode(line);
        }

        case TOKEN_LEFT_BRACE:
            return parse_block();

        case TOKEN_SEMICOLON:
            line = currentToken.line;  // 记录分号的行号
            advance(); // 消耗 ';'
            return createEmptyStmtNode(line);

        case TOKEN_RETURN: {
            line = currentToken.line;
            advance(); // 消耗 'return'

            ASTNode* expr = NULL;
            // 检查是否有返回值表达式
            if (peek() != TOKEN_SEMICOLON) {
                expr = parse_expr();
            }

            // 检查结束分号
            if (!match(TOKEN_SEMICOLON)) {
                handleParserError(ERROR_MISSING_RETURN_SEMICOLON);
                // 错误恢复：跳过直到分号
                while (peek() != TOKEN_SEMICOLON &&
                       peek() != TOKEN_RIGHT_BRACE &&
                       peek() != TOKEN_EOF) {
                    advance();
                }
                if (peek() == TOKEN_SEMICOLON) advance();
            }

            return createReturnNode(expr, line);
        }

            // 处理声明语句
        case TOKEN_INT:
        case TOKEN_CHAR:
        case TOKEN_FLOAT:
        case TOKEN_DOUBLE:
        case TOKEN_VOID:
            return parse_declaration();

        default: {
            line = currentToken.line;  // 记录表达式起始行号
            // 尝试解析表达式语句
            if (peek() == TOKEN_NUMBER ||
                peek() == TOKEN_IDENTIFIER ||
                peek() == TOKEN_LEFT_PAREN) {

                ASTNode* expr = parse_expr();
                if (expr && match(TOKEN_SEMICOLON)) {
                    return createExprStmtNode(expr, line);
                } else {
                    handleParserError(ERROR_MISSING_SEMICOLON);
                    // 错误恢复：向前扫描直到找到分号或语句结束符
                    while (peek() != TOKEN_SEMICOLON &&
                           peek() != TOKEN_RIGHT_BRACE &&
                           peek() != TOKEN_EOF) {
                        advance();
                    }
                    if (peek() == TOKEN_SEMICOLON) advance();
                    return expr; // 返回部分解析的表达式或NULL
                }
            } else {
                // 无法识别的语句起始符
                handleParserError(ERROR_UNKNOWN_STATEMENT);
                // 错误恢复：跳过当前token
                advance();
                return NULL;
            }
        }
    }
}

// 解析块语句
ASTNode* parse_block() {
    int line = currentToken.line;  // 记录左大括号的行号
    if (!match(TOKEN_LEFT_BRACE)) {
        return NULL;
    }

    int stmtCount = 0;
    ASTNode** statements = NULL;

    while (peek() != TOKEN_RIGHT_BRACE && peek() != TOKEN_EOF) {
        ASTNode* stmt = parse_statement();
        if (stmt) {
            statements = realloc(statements, (stmtCount + 1) * sizeof(ASTNode*));
            statements[stmtCount++] = stmt;
        }
    }

    if (!match(TOKEN_RIGHT_BRACE)) {
        handleParserError(ERROR_MISSING_RIGHT_BRACE);
        return NULL;
    }

    ASTNode* block = createBlockNode(stmtCount, line);
    if (stmtCount > 0) {
        memcpy(block->children, statements, stmtCount * sizeof(ASTNode*));
    }
    free(statements);
    return block;
}
/*-------------------------------------->解析程序<-----------------------------------------*/
// 解析程序
ASTNode* parse_program() {
    int line = 1;
    int declCount = 0;
    ASTNode** declarations = NULL;

    while (peek() != TOKEN_EOF) {
        ASTNode* node = NULL;

        // 先尝试解析函数定义
        if (peek() == TOKEN_INT || peek() == TOKEN_CHAR ||
            peek() == TOKEN_FLOAT || peek() == TOKEN_DOUBLE ||
            peek() == TOKEN_VOID) {

            // 保存当前状态以便回退
            const char* saved = lexer.current;
            int savedLine = lexer.line;

            ASTNode* func = parse_function_def();
            if (func) {
                node = func;
            } else {
                // 回退到类型说明符前
                lexer.current = saved;
                lexer.line = savedLine;
                currentToken = lexerIdentifier();
            }
        }

        // 如果不是函数定义，则解析语句
        if (!node) {
            node = parse_statement();
        }

        if (node) {
            declarations = realloc(declarations, (declCount + 1) * sizeof(ASTNode*));
            declarations[declCount++] = node;
        } else {
            // 更精确的错误恢复：跳过当前token
            advance();
        }
    }

    ASTNode* program = createASTNode(AST_PROGRAM, declCount, line);
    if (declCount > 0) {
        program->children = declarations;
    }
    program->data.program.declarations = declarations;
    program->data.program.declCount = declCount;
    return program;
}
/********************************************************************************************
 *                                           分句	 									    *
 ********************************************************************************************/

// 主分析函数
ASTNode* parse(const char* source) {
    initLexer(source);
    resetLexer();  // 重置词法分析器状态
    advance();
    return parse_program();
}